import React, { Component } from 'react'
import request from '../../util/request'

interface Iprops{
    history:any
}

interface Istate{
    username:string,
    password:any,
    [propName:string]:any  //添加任意多的属性
}   

export default class Login extends Component<Iprops,Istate> {
    state = {
        username:'',
        password:''
    }
    render() {
        let {username,password} = this.state;
        return (
            <div>
                用户名：<input type="text" name="username" value={username} onChange={this.change}></input>
                密码：<input type="password" name="password" value={password} onChange={this.change}></input>
                <button onClick={this.login}>登录</button>
            </div>
        )
    }

    change = (e:any) => {
        // e.target.value  e.target.name
        this.setState({
            [e.target.name]:e.target.value
        })
    }

    login = () => {
        let {username,password} = this.state;
        if(username && password){
            request.post('/api/login',{username,password}).then(res => {
                if(res.data.code === 1){
                    //token存在本地
                    localStorage.setItem('token',res.data.token);
                    localStorage.setItem('username',username);
                    alert("登录成功");
                    this.props.history.push('/main/home')
                }else{
                    alert("登录失败")
                }
            })
        }
    }
}
